package cn.com.shopec.erp.purchase.dao.impl;

import org.hibernate.Query;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.stereotype.Repository;

import cn.com.shopec.erp.common.orm.impl.HibernateEntityDao;
import cn.com.shopec.erp.purchase.dao.IStockPurchaseDao;
import cn.com.shopec.erp.purchase.entity.StockPurchase;

@Repository
public class StockPurchaseDaoImpl extends HibernateEntityDao<StockPurchase> implements IStockPurchaseDao{

	@Override
	public StockPurchase getStockPurchaseByPoNo(String id, String poNo) {
		
		StockPurchase stockPurchase = null;
		if(id != null && poNo != null){
			StringBuffer sql = new StringBuffer();
			sql.append("SELECT "
					+ "t.id as id,"
					+ "t.poNo as poNo,"
					+ "t.stockNo as stockNo,"
					+ "t.commonNumner as commonNumner,"
					+ "t.remainingAmount as remainingAmount,"
					+ "t.createTime as createTime,"
					+ "t.defectiveAmountNumber as defectiveAmountNumber,"
					+ "t.defectiveNumber as defectiveNumber,"
					+ "t.yieldAmountNumner as yieldAmountNumner,"
					+ "t.yieldNumner as yieldNumner"
					+ " from TBL_STOCK_PURCHASE t "
					+ "where t.id = '"+id+"' and t.poNo = '"+poNo+"' ");
			Query query= getSession().createSQLQuery(sql.toString())
					.addScalar("id",StandardBasicTypes.STRING)
					.addScalar("poNo",StandardBasicTypes.STRING)
					.addScalar("stockNo",StandardBasicTypes.STRING)
					.addScalar("commonNumner",StandardBasicTypes.LONG)
					.addScalar("remainingAmount",StandardBasicTypes.LONG)
					.addScalar("createTime",StandardBasicTypes.STRING)
					.addScalar("yieldNumner",StandardBasicTypes.LONG)
					.addScalar("yieldAmountNumner",StandardBasicTypes.LONG)
					.addScalar("defectiveNumber",StandardBasicTypes.LONG)
					.addScalar("defectiveAmountNumber",StandardBasicTypes.LONG);
			query.setResultTransformer(Transformers.aliasToBean(StockPurchase.class));
			stockPurchase = (StockPurchase) query.uniqueResult();
		}
		return stockPurchase;
		
	}

	@Override
	public int changeQuantity(StockPurchase stockPurchase) {
		String hql = "update StockPurchase as p set "
				+ " p.yieldAmountNumner = yieldAmountNumner + :yieldAmountNumner,"
				+ " p.defectiveAmountNumber = defectiveAmountNumber + :defectiveAmountNumber"
				+ " where p.poNo = :poNo"
				+ " and p.prodNo = :prodNo"
				+ " and p.whNo = :whNo"
				+ " and yieldAmountNumner + :yieldAmountNumner >= 0"
				+ " and defectiveAmountNumber + :defectiveAmountNumber >= 0";
		int count = getSession()
				.createQuery(hql)
				.setParameter("poNo", stockPurchase.getPoNo())
				.setParameter("prodNo", stockPurchase.getProdNo())
				.setParameter("whNo", stockPurchase.getWhNo())
				.setParameter("yieldAmountNumner", stockPurchase.getYieldAmountNumner())
				.setParameter("defectiveAmountNumber", stockPurchase.getDefectiveAmountNumber())
				.executeUpdate();
		return count;
	}
}
